#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>

#include "stm32f10x.h"
#include "stm32f10x_spi.h"
#include "spi.h"

static s_spi_info info[2] = 
{
  0  
};

int spi_init(int spi_id, s_spi_info *p_info)
{
    if(p_info==NULL){return -1;}
    
    if((p_info->instance!=SPI1) && (p_info->instance!=SPI2)){return -1;}
    
    memcpy(&info[spi_id&0x01], p_info, sizeof(s_spi_info));
           
    if(p_info->instance == SPI2)    
    {
        GPIO_InitTypeDef GPIO_InitStructure;
        
        RCC_APB2PeriphClockCmd(    RCC_APB2Periph_GPIOB, ENABLE ); 
        RCC_APB1PeriphClockCmd(    RCC_APB1Periph_SPI2,  ENABLE );    
     
        GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13 | GPIO_Pin_14 | GPIO_Pin_15;
        GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;   
        GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
        GPIO_Init(GPIOB, &GPIO_InitStructure);

        GPIO_SetBits(GPIOB,GPIO_Pin_13|GPIO_Pin_14|GPIO_Pin_15);          
    }
        
    SPI_Init(p_info->instance, &p_info->cfg);  
    SPI_Cmd(p_info->instance, ENABLE); 
    SPI_CalculateCRC(p_info->instance, DISABLE);
   
    return 0;
}

u8 spi_readwrite(int spi_id, u8 data)
{
    if(info[spi_id&0x01].instance != NULL)
    {
        u8 retry=0, id= spi_id&0x01;    
        
        while (SPI_I2S_GetFlagStatus(info[id].instance, SPI_I2S_FLAG_TXE) == RESET) 
        {
            retry++;
            if(retry>200)
            {
                return 0;
            }
        }              
        SPI_I2S_SendData(info[id].instance, data); 
        retry=0;

        while (SPI_I2S_GetFlagStatus(info[id].instance, SPI_I2S_FLAG_RXNE) == RESET) 
        {
            retry++;
            if(retry>200)
            {
                return 0;
            }
        }                                  
        return SPI_I2S_ReceiveData(info[id].instance);     
    }    
    return 0;
}

char get_spi_user(int spi_id)
{
    return info[spi_id&0x01].user;
}
